<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 有单做
 -->
<template>
  <div>
    <van-form class="single">
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.user_pass"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <div class="popup-open__form-code">
        <van-field
          v-model="ruleForm.captcha"
          type="tel"
          label="验证码"
          placeholder="请填写验证码"
          clearable
        />
        <van-image :src="imageSrc" @click="onGetCaptcha">
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <!-- <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>-->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onLogin">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import * as single from "@/api/single";
import { JSEncrypt } from "jsencrypt";
import { alertMsg } from "@/utils/index";
export default {
  name: "Single",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        mobile: "17796963895",
        user_pass: "Zz930329",
        _captcha_id: "LAY-user-get-vercode",
        captcha: ""
      },
      imageSrc: "",
      IntervalTime: 3,
      type: "0",
      startFlag: false,
      timer: null,
      returnContent: [],
      activeIndex: "",
      isAcceptSuc: false,
      publicKey:
        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEAQnLqKDERepmXQyLoHpz3jpDO5I6Pyw2IhijiAN1Uhc12EpCvgUdoaCYV31sKGnRkXnaoJHspLWmGtznND6mXMlPEEg0VCOjRJoa6AH9hjmqz+vdgJJdjHef+nOV6BrsQLiMO8Nho5FlFZkPkEWHpKhfb3lsmujZZzx6bO+GwwIDAQAB",
      cookie: ''
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 23 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 23 && this.index !== "") {
        this.onGetCaptcha();
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.mobile = this.item.user;
        this.ruleForm.user_pass = this.item.pass;
        this.type = this.item.type || "0";
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 23 && this.index !== "") {
      this.onGetCaptcha();
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.mobile = this.item.user;
      this.ruleForm.user_pass = this.item.pass;
      this.type = this.item.type || "0";
    }
  },
  methods: {
    // 获取验证码
    onGetCaptcha() {
      const _this = this;
      let time = Math.random();
      this.imageSrc = "";
      this.$ajax({
          url: single.getCaptcha,
          type: "get",
          ajaxData: {
            values: {
              id: 'LAY-user-get-vercode',
              height: '37',
              width: '130',
              "font_size": '18',
              time: time
            }
          },
          returnAll: true,
          dataType: 'text',
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-Requested-With": "XMLHttpRequest"
          },
          method: function() {
           _this.imageSrc =
              single.getCaptcha +
              "?id=LAY-user-get-vercode&height=37&height=37&width=130&font_size=18&time=" +
              time;
          }
      });
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        single.ajaxFun(
          single.getLogin,
          {
            type: "post",
            data: {
              mobile: this.ruleForm.mobile,
              user_pass: this.encryptedData(
                this.publicKey,
                this.ruleForm.user_pass
              ),
              _captcha_id: "LAY-user-get-vercode",
              captcha: this.ruleForm.captcha
            }
          },
          () => {
            _this.returnContent.unshift(alertMsg("登录成功"));

          }
        );
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 加密密码
    encryptedData(publicKey, data) {
      // var n = "-----BEGIN PUBLIC KEY-----\r\n";
      // n += publicKey;
      // n += "\r\n-----END PUBLIC KEY-----";
      // 新建JSEncrypt对象
      let encryptor = new JSEncrypt();
      // 设置公钥
      encryptor.setPublicKey(publicKey);
      // 加密数据
      return encryptor.encrypt(data);
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>